function ff = vec2leg(f,n,dir,ord)
% function vec2leg(f,n,dir,ord)
% this function either 
%   dir=1) takes an n-vector f and returns the discrete legendre polynomial
%          expansion coefficients up to order ord
% or 
%   dir=2) take a vector of such coefficients and builds an approximate
%          vector of length n


% determine legendre polynomials
N           = sum(n)-1;    % max degree
k           = 0:N;         % interval
P           = zeros(ord+1,N+1);
P(1,1:N+1)  = 1;
P(2,1:N+1)  = 1 - (2*k)/N;
for j = 3:ord+1 %otherwise N-1
    i = j-2;
    P(i+2,1:N+1) = ( (2*i+1)*(N-2*k).*P(i+1,:) - i*(N+i+1)*P(i,:) ) ./ ...
        ((i+1)*(N-i)) ;
end
for i = 0:ord
    a = (2*i+1);
    b = factorial(N+i+1)/factorial(N);
    c = factorial(N)/factorial(N-i);
    w(i+1)=a*c/b;
end

if dir == 1
    for i=1:ord+1
        ff(i) = w(i)*f'*P(i,:)';
    end
else
    ff = zeros(n,1);
    for i = 1:ord+1
        ff  = ff + f(i)*P(i,:)';
    end  
end
    
    
end

